<?php
/**
 * Created by PhpStorm.
 * User: Keter
 * Date: 2016/8/3
 * Time: 17:00
 */
if (!defined("MAJIANG_DIR")) {
    define("MAJIANG_DIR", dirname(__FILE__));
}

date_default_timezone_set('Asia/Shanghai');
error_reporting(E_ALL ^ E_NOTICE);

spl_autoload_register('autoload');

$logger_filename = __DIR__ . "/data/logs/php_".date("Ymd").".log";

if (!file_exists($logger_filename)) {
    @touch($logger_filename);
}
if (!is_writable($logger_filename)) {
    @chmod($logger_filename, 755);
}
GlobalConfig::$logger = new Logger($logger_filename);

/**
 * 常量定义
 */
define('_SPACE', chr(32));

/**
 * 运行环境判断
 */
define('_APP_MODE', getApplicationMode());

/**
 * 应用程序类
 */
class Application
{
    /**
     * 运行
     * @param string $type
     */
    public static function run($type = 'interface')
    {
        $className = null;

        if (isset($_GET['request'])) {
            $className = $_GET['request'];
        } else {
            self::printError("action no found.");
        }

        $file = pathFormat($type . "/" . $className . ".php");

        if (file_exists($file)) {
            include_once($file);
            $cmd = new $className;
            $cmd->exec_logic();
        } else {
            self::printError("file no found.");
        }
    }

    /**
     * 打印错误
     * @param $msg
     * @param int $status
     * @param int $code
     */
    public static function printError($msg, $status = -1, $code = 0)
    {
        echo json_encode(array('status' => $status, "desc" => $msg));
        exit(1);
    }
}

/**
 * 路径生成
 * @param $file
 * @return string
 */
function pathFormat($file) {
    return str_replace("\\", '/', MAJIANG_DIR . "/" . $file);
}

/**
 * 获取运行模式
 */
function getApplicationMode()
{
    $lockFile = pathFormat('lock.php');
    $appConfigFile = pathFormat('config/test.php');

    if (file_exists($lockFile) && file_exists($appConfigFile)) {
        $mode = include('lock.php');
        if ($mode && $mode !== 'product') {
            include_once ($appConfigFile);
            if (TestConfig::$run_mode === $mode) {
                return $mode;
            }
        }
    }

    return 'product';
}

/**
 * 类的自动加载
 * @param $className
 * @return bool
 */
function autoload($class)
{
    if (strstr($class, '/')) {
        $className = substr($class, strrpos($class, '/') + 1);
    } elseif (strstr($class, "\\")) {
        $className = substr($class, strrpos($class, "\\") + 1);
    } else {
        $className = $class;
    }

    if (substr($class, -6) == 'Config') {
        $dir = 'config';
        $class = lcfirst(substr($class, 0, strrpos($class, 'Config')));
    } else {
        $dir = 'classes';
    }

    $file = pathFormat($dir . '/' . $class . '.php');

    if (is_file($file)) {
        include_once($file);
        if (class_exists($className, false)) {
            return true;
        }
    }

    $autoloads = spl_autoload_functions();
    foreach ($autoloads as $val) {
        if ($val != __FUNCTION__) {
            return call_user_func($val, $className);
        }
    }

    Application::printError("Class {$class} not found.");
}
